3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
18 define( 'MW_PARSER_VERSION', '1.6.0' );
21 * Variable substitution O(N^2) attack
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
33 define( 'RLH_FOR_UPDATE', 1 );
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
64 * Processes wiki markup
67 * There are three main entry points into the Parser class:
69 * produces HTML output
71 * produces altered wiki markup.
73 * performs brace substitution on MediaWiki messages
76 * objects: $wgLang, $wgContLang
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
85 * * only within ParserOptions
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mTemplates, // cache of already loaded templates, avoids
103 // multiple SQL queries for the same string
104 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
105 // in this path. Used for loop detection.
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
122 $this->mTagHooks
= array();
131 function clearState() {
132 $this->mOutput
= new ParserOutput
;
133 $this->mAutonumber
= 0;
134 $this->mLastSection
= '';
135 $this->mDTopen
= false;
136 $this->mVariables
= false;
137 $this->mIncludeCount
= array();
138 $this->mStripState
= array();
139 $this->mArgStack
= array();
140 $this->mInPre
= false;
141 $this->mInterwikiLinkHolders
= array(
145 $this->mLinkHolders
= array(
146 'namespaces' => array(),
148 'queries' => array(),
152 $this->mRevisionId
= null;
153 $this->mUniqPrefix
= 'UNIQ' . Parser
::getRandomString();
155 # Clear these on every parse, bug 4549
156 $this->mTemplates
= array();
157 $this->mTemplatePath
= array();
159 wfRunHooks( 'ParserClearState', array( &$this ) );
163 * Accessor for mUniqPrefix.
167 function UniqPrefix() {
168 return $this->mUniqPrefix
;
172 * Convert wikitext to HTML
173 * Do not call this function recursively.
176 * @param string $text Text we want to parse
177 * @param Title &$title A title object
178 * @param array $options
179 * @param boolean $linestart
180 * @param boolean $clearState
181 * @param int $revid number to pass in {{REVISIONID}}
182 * @return ParserOutput a ParserOutput
184 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
186 * First pass--just handle <nowiki> sections, pass the rest off
187 * to internalParse() which does all the real work.
190 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
191 $fname = 'Parser::parse';
192 wfProfileIn( $fname );
198 $this->mOptions
= $options;
199 $this->mTitle
=& $title;
200 $this->mRevisionId
= $revid;
201 $this->mOutputType
= OT_HTML
;
203 $this->mStripState
= NULL;
205 //$text = $this->strip( $text, $this->mStripState );
206 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
207 $x =& $this->mStripState
;
209 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
210 $text = $this->strip( $text, $x );
211 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
213 # Hook to suspend the parser in this state
214 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
215 wfProfileOut( $fname );
219 $text = $this->internalParse( $text );
221 $text = $this->unstrip( $text, $this->mStripState
);
223 # Clean up special characters, only run once, next-to-last before doBlockLevels
225 # french spaces, last one Guillemet-left
226 # only if there is something before the space
227 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
228 # french spaces, Guillemet-right
229 '/(\\302\\253) /' => '\\1 ',
230 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
232 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
235 $text = $this->doBlockLevels( $text, $linestart );
237 $this->replaceLinkHolders( $text );
239 # the position of the parserConvert() call should not be changed. it
240 # assumes that the links are all replaced and the only thing left
241 # is the <nowiki> mark.
242 # Side-effects: this calls $this->mOutput->setTitleText()
243 $text = $wgContLang->parserConvert( $text, $this );
245 $text = $this->unstripNoWiki( $text, $this->mStripState
);
247 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
249 $text = Sanitizer
::normalizeCharReferences( $text );
251 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
252 $text = Parser
::tidy($text);
254 # attempt to sanitize at least some nesting problems
255 # (bug #2702 and quite a few others)
257 # ''Something [http://www.cool.com cool''] -->
258 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
259 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
260 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
261 # fix up an anchor inside another anchor, only
262 # at least for a single single nested link (bug 3695)
263 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
264 '\\1\\2</a>\\3</a>\\1\\4</a>',
265 # fix div inside inline elements- doBlockLevels won't wrap a line which
266 # contains a div, so fix it up here; replace
267 # div with escaped text
268 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
269 '\\1\\3<div\\5>\\6</div>\\8\\9',
270 # remove empty italic or bold tag pairs, some
271 # introduced by rules above
272 '/<([bi])><\/\\1>/' => ''
275 $text = preg_replace(
276 array_keys( $tidyregs ),
277 array_values( $tidyregs ),
281 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
283 $this->mOutput
->setText( $text );
284 wfProfileOut( $fname );
286 return $this->mOutput
;
290 * Get a random string
295 function getRandomString() {
296 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
299 function &getTitle() { return $this->mTitle
; }
300 function getOptions() { return $this->mOptions
; }
303 * Replaces all occurrences of <$tag>content</$tag> in the text
304 * with a random marker and returns the new text. the output parameter
305 * $content will be an associative array filled with data on the form
306 * $unique_marker => content.
308 * If $content is already set, the additional entries will be appended
309 * If $tag is set to STRIP_COMMENTS, the function will extract
310 * <!-- HTML comments -->
315 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
316 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
331 if( $tag == STRIP_COMMENTS
) {
332 $start = '/<!--()()/';
335 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
336 $end = "/<\\/$tag\\s*>/i";
339 while ( '' != $text ) {
340 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
342 if( count( $p ) < 4 ) {
349 $marker = $rnd . sprintf('%08X', $n++
);
350 $stripped .= $marker;
352 $tags[$marker] = "<$tag$attributes$empty>";
353 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
355 if ( $empty === '/' ) {
356 // Empty element tag, <tag />
357 $content[$marker] = null;
360 $q = preg_split( $end, $inside, 2 );
361 $content[$marker] = $q[0];
362 if( count( $q ) < 2 ) {
363 # No end tag -- let it run out to the end of the text.
374 * Wrapper function for extractTagsAndParams
375 * for cases where $tags and $params isn't needed
376 * i.e. where tags will never have params, like <nowiki>
381 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
382 $dummy_tags = array();
383 $dummy_params = array();
385 return Parser
::extractTagsAndParams( $tag, $text, $content,
386 $dummy_tags, $dummy_params, $uniq_prefix );
390 * Strips and renders nowiki, pre, math, hiero
391 * If $render is set, performs necessary rendering operations on plugins
392 * Returns the text, and fills an array with data needed in unstrip()
393 * If the $state is already a valid strip state, it adds to the state
395 * @param bool $stripcomments when set, HTML comments <!-- like this -->
396 * will be stripped in addition to other tags. This is important
397 * for section editing, where these comments cause confusion when
398 * counting the sections in the wikisource
402 function strip( $text, &$state, $stripcomments = false ) {
403 $render = ($this->mOutputType
== OT_HTML
);
404 $html_content = array();
405 $nowiki_content = array();
406 $math_content = array();
407 $pre_content = array();
408 $comment_content = array();
409 $ext_content = array();
411 $ext_params = array();
412 $gallery_content = array();
414 # Replace any instances of the placeholders
415 $uniq_prefix = $this->mUniqPrefix
;
416 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
421 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
422 foreach( $html_content as $marker => $content ) {
424 # Raw and unchecked for validity.
425 $html_content[$marker] = $content;
427 $html_content[$marker] = '<html>'.$content.'</html>';
433 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
434 foreach( $nowiki_content as $marker => $content ) {
436 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
438 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
443 if( $this->mOptions
->getUseTeX() ) {
444 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
445 foreach( $math_content as $marker => $content ){
447 $math_content[$marker] = renderMath( $content );
449 $math_content[$marker] = '<math>'.$content.'</math>';
455 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
456 foreach( $pre_content as $marker => $content ){
458 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
460 $pre_content[$marker] = '<pre>'.$content.'</pre>';
465 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
466 foreach( $gallery_content as $marker => $content ) {
467 require_once( 'ImageGallery.php' );
469 $gallery_content[$marker] = $this->renderImageGallery( $content );
471 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
477 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
478 foreach( $comment_content as $marker => $content ){
479 $comment_content[$marker] = '<!--'.$content.'-->';
484 foreach ( $this->mTagHooks
as $tag => $callback ) {
485 $ext_content[$tag] = array();
486 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
487 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
488 foreach( $ext_content[$tag] as $marker => $content ) {
489 $full_tag = $ext_tags[$tag][$marker];
490 $params = $ext_params[$tag][$marker];
492 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
494 if ( is_null( $content ) ) {
496 $ext_content[$tag][$marker] = $full_tag;
498 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
504 # Merge state with the pre-existing state, if there is one
506 $state['html'] = $state['html'] +
$html_content;
507 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
508 $state['math'] = $state['math'] +
$math_content;
509 $state['pre'] = $state['pre'] +
$pre_content;
510 $state['gallery'] = $state['gallery'] +
$gallery_content;
511 $state['comment'] = $state['comment'] +
$comment_content;
513 foreach( $ext_content as $tag => $array ) {
514 if ( array_key_exists( $tag, $state ) ) {
515 $state[$tag] = $state[$tag] +
$array;
520 'html' => $html_content,
521 'nowiki' => $nowiki_content,
522 'math' => $math_content,
523 'pre' => $pre_content,
524 'gallery' => $gallery_content,
525 'comment' => $comment_content,
532 * restores pre, math, and hiero removed by strip()
534 * always call unstripNoWiki() after this one
537 function unstrip( $text, &$state ) {
538 if ( !is_array( $state ) ) {
542 # Must expand in reverse order, otherwise nested tags will be corrupted
543 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
544 if( $tag != 'nowiki' && $tag != 'html' ) {
545 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
546 $text = str_replace( $uniq, $content, $text );
555 * always call this after unstrip() to preserve the order
559 function unstripNoWiki( $text, &$state ) {
560 if ( !is_array( $state ) ) {
564 # Must expand in reverse order, otherwise nested tags will be corrupted
565 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
566 $text = str_replace( key( $state['nowiki'] ), $content, $text );
571 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
572 $text = str_replace( key( $state['html'] ), $content, $text );
580 * Add an item to the strip state
581 * Returns the unique tag which must be inserted into the stripped text
582 * The tag will be replaced with the original text in unstrip()
586 function insertStripItem( $text, &$state ) {
587 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
594 'comment' => array(),
595 'gallery' => array(),
598 $state['item'][$rnd] = $text;
603 * Interface with html tidy, used if $wgUseTidy = true.
604 * If tidy isn't able to correct the markup, the original will be
605 * returned in all its glory with a warning comment appended.
607 * Either the external tidy program or the in-process tidy extension
608 * will be used depending on availability. Override the default
609 * $wgTidyInternal setting to disable the internal if it's not working.
611 * @param string $text Hideous HTML input
612 * @return string Corrected HTML output
616 function tidy( $text ) {
617 global $wgTidyInternal;
618 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
619 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
620 '<head><title>test</title></head><body>'.$text.'</body></html>';
621 if( $wgTidyInternal ) {
622 $correctedtext = Parser
::internalTidy( $wrappedtext );
624 $correctedtext = Parser
::externalTidy( $wrappedtext );
626 if( is_null( $correctedtext ) ) {
627 wfDebug( "Tidy error detected!\n" );
628 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
630 return $correctedtext;
634 * Spawn an external HTML tidy process and get corrected markup back from it.
639 function externalTidy( $text ) {
640 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
641 $fname = 'Parser::externalTidy';
642 wfProfileIn( $fname );
647 $descriptorspec = array(
648 0 => array('pipe', 'r'),
649 1 => array('pipe', 'w'),
650 2 => array('file', '/dev/null', 'a')
653 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
654 if (is_resource($process)) {
655 // Theoretically, this style of communication could cause a deadlock
656 // here. If the stdout buffer fills up, then writes to stdin could
657 // block. This doesn't appear to happen with tidy, because tidy only
658 // writes to stdout after it's finished reading from stdin. Search
659 // for tidyParseStdin and tidySaveStdout in console/tidy.c
660 fwrite($pipes[0], $text);
662 while (!feof($pipes[1])) {
663 $cleansource .= fgets($pipes[1], 1024);
666 proc_close($process);
669 wfProfileOut( $fname );
671 if( $cleansource == '' && $text != '') {
672 // Some kind of error happened, so we couldn't get the corrected text.
673 // Just give up; we'll use the source text and append a warning.
681 * Use the HTML tidy PECL extension to use the tidy library in-process,
682 * saving the overhead of spawning a new process. Currently written to
683 * the PHP 4.3.x version of the extension, may not work on PHP 5.
685 * 'pear install tidy' should be able to compile the extension module.
690 function internalTidy( $text ) {
692 $fname = 'Parser::internalTidy';
693 wfProfileIn( $fname );
695 tidy_load_config( $wgTidyConf );
696 tidy_set_encoding( 'utf8' );
697 tidy_parse_string( $text );
699 if( tidy_get_status() == 2 ) {
700 // 2 is magic number for fatal error
701 // http://www.php.net/manual/en/function.tidy-get-status.php
704 $cleansource = tidy_get_output();
706 wfProfileOut( $fname );
711 * parse the wiki syntax used to render tables
715 function doTableStuff ( $t ) {
716 $fname = 'Parser::doTableStuff';
717 wfProfileIn( $fname );
719 $t = explode ( "\n" , $t ) ;
720 $td = array () ; # Is currently a td tag open?
721 $ltd = array () ; # Was it TD or TH?
722 $tr = array () ; # Is currently a tr tag open?
723 $ltr = array () ; # tr attributes
724 $has_opened_tr = array(); # Did this table open a <tr> element?
725 $indent_level = 0; # indent level of the table
726 foreach ( $t AS $k => $x )
729 $fc = substr ( $x , 0 , 1 ) ;
730 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
731 $indent_level = strlen( $matches[1] );
733 $attributes = $this->unstripForHTML( $matches[2] );
735 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
736 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
737 array_push ( $td , false ) ;
738 array_push ( $ltd , '' ) ;
739 array_push ( $tr , false ) ;
740 array_push ( $ltr , '' ) ;
741 array_push ( $has_opened_tr, false );
743 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
744 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
745 $z = "</table>" . substr ( $x , 2);
746 $l = array_pop ( $ltd ) ;
747 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
748 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
749 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
751 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
753 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
754 $x = substr ( $x , 1 ) ;
755 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
757 $l = array_pop ( $ltd ) ;
758 array_pop ( $has_opened_tr );
759 array_push ( $has_opened_tr , true ) ;
760 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
761 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
764 array_push ( $tr , false ) ;
765 array_push ( $td , false ) ;
766 array_push ( $ltd , '' ) ;
767 $attributes = $this->unstripForHTML( $x );
768 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
770 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
772 if ( '|+' == substr ( $x , 0 , 2 ) ) {
774 $x = substr ( $x , 1 ) ;
776 $after = substr ( $x , 1 ) ;
777 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
778 $after = explode ( '||' , $after ) ;
781 # Loop through each table cell
782 foreach ( $after AS $theline )
787 $tra = array_pop ( $ltr ) ;
788 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
789 array_push ( $tr , true ) ;
790 array_push ( $ltr , '' ) ;
791 array_pop ( $has_opened_tr );
792 array_push ( $has_opened_tr , true ) ;
795 $l = array_pop ( $ltd ) ;
796 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
797 if ( $fc == '|' ) $l = 'td' ;
798 else if ( $fc == '!' ) $l = 'th' ;
799 else if ( $fc == '+' ) $l = 'caption' ;
801 array_push ( $ltd , $l ) ;
804 $y = explode ( '|' , $theline , 2 ) ;
805 # Note that a '|' inside an invalid link should not
806 # be mistaken as delimiting cell parameters
807 if ( strpos( $y[0], '[[' ) !== false ) {
808 $y = array ($theline);
810 if ( count ( $y ) == 1 )
811 $y = "{$z}<{$l}>{$y[0]}" ;
813 $attributes = $this->unstripForHTML( $y[0] );
814 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
817 array_push ( $td , true ) ;
822 # Closing open td, tr && table
823 while ( count ( $td ) > 0 )
825 $l = array_pop ( $ltd ) ;
826 if ( array_pop ( $td ) ) $t[] = '</td>' ;
827 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
828 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
832 $t = implode ( "\n" , $t ) ;
833 # special case: don't return empty table
834 if($t == "<table>\n<tr><td></td></tr>\n</table>")
836 wfProfileOut( $fname );
841 * Helper function for parse() that transforms wiki markup into
842 * HTML. Only called for $mOutputType == OT_HTML.
846 function internalParse( $text ) {
849 $fname = 'Parser::internalParse';
850 wfProfileIn( $fname );
852 # Remove <noinclude> tags and <includeonly> sections
853 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
854 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
855 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
857 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
858 $text = $this->replaceVariables( $text, $args );
860 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
862 $text = $this->doHeadings( $text );
863 if($this->mOptions
->getUseDynamicDates()) {
864 $df =& DateFormatter
::getInstance();
865 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
867 $text = $this->doAllQuotes( $text );
868 $text = $this->replaceInternalLinks( $text );
869 $text = $this->replaceExternalLinks( $text );
871 # replaceInternalLinks may sometimes leave behind
872 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
873 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
875 $text = $this->doMagicLinks( $text );
876 $text = $this->doTableStuff( $text );
877 $text = $this->formatHeadings( $text, $isMain );
879 wfProfileOut( $fname );
884 * Replace special strings like "ISBN xxx" and "RFC xxx" with
885 * magic external links.
889 function &doMagicLinks( &$text ) {
890 $text = $this->magicISBN( $text );
891 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
892 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
897 * Parse headers and return html
901 function doHeadings( $text ) {
902 $fname = 'Parser::doHeadings';
903 wfProfileIn( $fname );
904 for ( $i = 6; $i >= 1; --$i ) {
905 $h = str_repeat( '=', $i );
906 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
907 "<h{$i}>\\1</h{$i}>\\2", $text );
909 wfProfileOut( $fname );
914 * Replace single quotes with HTML markup
916 * @return string the altered text
918 function doAllQuotes( $text ) {
919 $fname = 'Parser::doAllQuotes';
920 wfProfileIn( $fname );
922 $lines = explode( "\n", $text );
923 foreach ( $lines as $line ) {
924 $outtext .= $this->doQuotes ( $line ) . "\n";
926 $outtext = substr($outtext, 0,-1);
927 wfProfileOut( $fname );
932 * Helper function for doAllQuotes()
935 function doQuotes( $text ) {
936 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
937 if ( count( $arr ) == 1 )
941 # First, do some preliminary work. This may shift some apostrophes from
942 # being mark-up to being text. It also counts the number of occurrences
943 # of bold and italics mark-ups.
947 foreach ( $arr as $r )
949 if ( ( $i %
2 ) == 1 )
951 # If there are ever four apostrophes, assume the first is supposed to
952 # be text, and the remaining three constitute mark-up for bold text.
953 if ( strlen( $arr[$i] ) == 4 )
958 # If there are more than 5 apostrophes in a row, assume they're all
959 # text except for the last 5.
960 else if ( strlen( $arr[$i] ) > 5 )
962 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
965 # Count the number of occurrences of bold and italics mark-ups.
966 # We are not counting sequences of five apostrophes.
967 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
968 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
969 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
974 # If there is an odd number of both bold and italics, it is likely
975 # that one of the bold ones was meant to be an apostrophe followed
976 # by italics. Which one we cannot know for certain, but it is more
977 # likely to be one that has a single-letter word before it.
978 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
981 $firstsingleletterword = -1;
982 $firstmultiletterword = -1;
984 foreach ( $arr as $r )
986 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
988 $x1 = substr ($arr[$i-1], -1);
989 $x2 = substr ($arr[$i-1], -2, 1);
991 if ($firstspace == -1) $firstspace = $i;
992 } else if ($x2 == ' ') {
993 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
995 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1001 # If there is a single-letter word, use it!
1002 if ($firstsingleletterword > -1)
1004 $arr [ $firstsingleletterword ] = "''";
1005 $arr [ $firstsingleletterword-1 ] .= "'";
1007 # If not, but there's a multi-letter word, use that one.
1008 else if ($firstmultiletterword > -1)
1010 $arr [ $firstmultiletterword ] = "''";
1011 $arr [ $firstmultiletterword-1 ] .= "'";
1013 # ... otherwise use the first one that has neither.
1014 # (notice that it is possible for all three to be -1 if, for example,
1015 # there is only one pentuple-apostrophe in the line)
1016 else if ($firstspace > -1)
1018 $arr [ $firstspace ] = "''";
1019 $arr [ $firstspace-1 ] .= "'";
1023 # Now let's actually convert our apostrophic mush to HTML!
1028 foreach ($arr as $r)
1032 if ($state == 'both')
1039 if (strlen ($r) == 2)
1042 { $output .= '</i>'; $state = ''; }
1043 else if ($state == 'bi')
1044 { $output .= '</i>'; $state = 'b'; }
1045 else if ($state == 'ib')
1046 { $output .= '</b></i><b>'; $state = 'b'; }
1047 else if ($state == 'both')
1048 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1049 else # $state can be 'b' or ''
1050 { $output .= '<i>'; $state .= 'i'; }
1052 else if (strlen ($r) == 3)
1055 { $output .= '</b>'; $state = ''; }
1056 else if ($state == 'bi')
1057 { $output .= '</i></b><i>'; $state = 'i'; }
1058 else if ($state == 'ib')
1059 { $output .= '</b>'; $state = 'i'; }
1060 else if ($state == 'both')
1061 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1062 else # $state can be 'i' or ''
1063 { $output .= '<b>'; $state .= 'b'; }
1065 else if (strlen ($r) == 5)
1068 { $output .= '</b><i>'; $state = 'i'; }
1069 else if ($state == 'i')
1070 { $output .= '</i><b>'; $state = 'b'; }
1071 else if ($state == 'bi')
1072 { $output .= '</i></b>'; $state = ''; }
1073 else if ($state == 'ib')
1074 { $output .= '</b></i>'; $state = ''; }
1075 else if ($state == 'both')
1076 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1077 else # ($state == '')
1078 { $buffer = ''; $state = 'both'; }
1083 # Now close all remaining tags. Notice that the order is important.
1084 if ($state == 'b' ||
$state == 'ib')
1086 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1090 if ($state == 'both')
1091 $output .= '<b><i>'.$buffer.'</i></b>';
1097 * Replace external links
1099 * Note: this is all very hackish and the order of execution matters a lot.
1100 * Make sure to run maintenance/parserTests.php if you change this code.
1104 function replaceExternalLinks( $text ) {
1106 $fname = 'Parser::replaceExternalLinks';
1107 wfProfileIn( $fname );
1109 $sk =& $this->mOptions
->getSkin();
1111 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1113 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1116 while ( $i<count( $bits ) ) {
1118 $protocol = $bits[$i++
];
1119 $text = $bits[$i++
];
1120 $trail = $bits[$i++
];
1122 # The characters '<' and '>' (which were escaped by
1123 # removeHTMLtags()) should not be included in
1124 # URLs, per RFC 2396.
1125 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1126 $text = substr($url, $m2[0][1]) . ' ' . $text;
1127 $url = substr($url, 0, $m2[0][1]);
1130 # If the link text is an image URL, replace it with an <img> tag
1131 # This happened by accident in the original parser, but some people used it extensively
1132 $img = $this->maybeMakeExternalImage( $text );
1133 if ( $img !== false ) {
1139 # Set linktype for CSS - if URL==text, link is essentially free
1140 $linktype = ($text == $url) ?
'free' : 'text';
1142 # No link text, e.g. [http://domain.tld/some.link]
1143 if ( $text == '' ) {
1144 # Autonumber if allowed
1145 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1146 $text = '[' . ++
$this->mAutonumber
. ']';
1147 $linktype = 'autonumber';
1149 # Otherwise just use the URL
1150 $text = htmlspecialchars( $url );
1154 # Have link text, e.g. [http://domain.tld/some.link text]s
1156 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1159 $text = $wgContLang->markNoConversion($text);
1161 # Replace & from obsolete syntax with &.
1162 # All HTML entities will be escaped by makeExternalLink()
1163 $url = str_replace( '&', '&', $url );
1165 # Process the trail (i.e. everything after this link up until start of the next link),
1166 # replacing any non-bracketed links
1167 $trail = $this->replaceFreeExternalLinks( $trail );
1169 # Use the encoded URL
1170 # This means that users can paste URLs directly into the text
1171 # Funny characters like ö aren't valid in URLs anyway
1172 # This was changed in August 2004
1173 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1175 # Register link in the output object.
1176 # Replace unnecessary URL escape codes with the referenced character
1177 # This prevents spammers from hiding links from the filters
1178 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1179 $this->mOutput
->addExternalLink( $pasteurized );
1182 wfProfileOut( $fname );
1187 * Replace anything that looks like a URL with a link
1190 function replaceFreeExternalLinks( $text ) {
1192 $fname = 'Parser::replaceFreeExternalLinks';
1193 wfProfileIn( $fname );
1195 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1196 $s = array_shift( $bits );
1199 $sk =& $this->mOptions
->getSkin();
1201 while ( $i < count( $bits ) ){
1202 $protocol = $bits[$i++
];
1203 $remainder = $bits[$i++
];
1205 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1206 # Found some characters after the protocol that look promising
1207 $url = $protocol . $m[1];
1210 # special case: handle urls as url args:
1211 # http://www.example.com/foo?=http://www.example.com/bar
1212 if(strlen($trail) == 0 &&
1214 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1215 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1218 $url .= $bits[$i] . $bits[$i +
1]; # protocol, url as arg to previous link
1223 # The characters '<' and '>' (which were escaped by
1224 # removeHTMLtags()) should not be included in
1225 # URLs, per RFC 2396.
1226 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1227 $trail = substr($url, $m2[0][1]) . $trail;
1228 $url = substr($url, 0, $m2[0][1]);
1231 # Move trailing punctuation to $trail
1233 # If there is no left bracket, then consider right brackets fair game too
1234 if ( strpos( $url, '(' ) === false ) {
1238 $numSepChars = strspn( strrev( $url ), $sep );
1239 if ( $numSepChars ) {
1240 $trail = substr( $url, -$numSepChars ) . $trail;
1241 $url = substr( $url, 0, -$numSepChars );
1244 # Replace & from obsolete syntax with &.
1245 # All HTML entities will be escaped by makeExternalLink()
1246 # or maybeMakeExternalImage()
1247 $url = str_replace( '&', '&', $url );
1249 # Is this an external image?
1250 $text = $this->maybeMakeExternalImage( $url );
1251 if ( $text === false ) {
1252 # Not an image, make a link
1253 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1254 # Register it in the output object...
1255 # Replace unnecessary URL escape codes with their equivalent characters
1256 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1257 $this->mOutput
->addExternalLink( $pasteurized );
1259 $s .= $text . $trail;
1261 $s .= $protocol . $remainder;
1264 wfProfileOut( $fname );
1269 * Replace unusual URL escape codes with their equivalent characters
1273 * @fixme This can merge genuinely required bits in the path or query string,
1274 * breaking legit URLs. A proper fix would treat the various parts of
1275 * the URL differently; as a workaround, just use the output for
1276 * statistical records, not for actual linking/output.
1278 function replaceUnusualEscapes( $url ) {
1279 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1280 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1284 * Callback function used in replaceUnusualEscapes().
1285 * Replaces unusual URL escape codes with their equivalent character
1289 function replaceUnusualEscapesCallback( $matches ) {
1290 $char = urldecode( $matches[0] );
1291 $ord = ord( $char );
1292 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1293 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1294 // No, shouldn't be escaped
1297 // Yes, leave it escaped
1303 * make an image if it's allowed, either through the global
1304 * option or through the exception
1307 function maybeMakeExternalImage( $url ) {
1308 $sk =& $this->mOptions
->getSkin();
1309 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1310 $imagesexception = !empty($imagesfrom);
1312 if ( $this->mOptions
->getAllowExternalImages()
1313 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1314 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1316 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1323 * Process [[ ]] wikilinks
1327 function replaceInternalLinks( $s ) {
1329 static $fname = 'Parser::replaceInternalLinks' ;
1331 wfProfileIn( $fname );
1333 wfProfileIn( $fname.'-setup' );
1335 # the % is needed to support urlencoded titles as well
1336 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1338 $sk =& $this->mOptions
->getSkin();
1340 #split the entire text string on occurences of [[
1341 $a = explode( '[[', ' ' . $s );
1342 #get the first element (all text up to first [[), and remove the space we added
1343 $s = array_shift( $a );
1344 $s = substr( $s, 1 );
1346 # Match a link having the form [[namespace:link|alternate]]trail
1348 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1349 # Match cases where there is no "]]", which might still be images
1350 static $e1_img = FALSE;
1351 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1352 # Match the end of a line for a word that's not followed by whitespace,
1353 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1354 $e2 = wfMsgForContent( 'linkprefix' );
1356 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1358 if( is_null( $this->mTitle
) ) {
1359 wfDebugDieBacktrace( 'nooo' );
1361 $nottalk = !$this->mTitle
->isTalkPage();
1363 if ( $useLinkPrefixExtension ) {
1364 if ( preg_match( $e2, $s, $m ) ) {
1365 $first_prefix = $m[2];
1367 $first_prefix = false;
1373 $selflink = $this->mTitle
->getPrefixedText();
1374 wfProfileOut( $fname.'-setup' );
1376 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1377 $useSubpages = $this->areSubpagesAllowed();
1379 # Loop for each link
1380 for ($k = 0; isset( $a[$k] ); $k++
) {
1382 if ( $useLinkPrefixExtension ) {
1383 wfProfileIn( $fname.'-prefixhandling' );
1384 if ( preg_match( $e2, $s, $m ) ) {
1392 $prefix = $first_prefix;
1393 $first_prefix = false;
1395 wfProfileOut( $fname.'-prefixhandling' );
1398 $might_be_img = false;
1400 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1402 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1403 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1404 # the real problem is with the $e1 regex
1407 # Still some problems for cases where the ] is meant to be outside punctuation,
1408 # and no image is in sight. See bug 2095.
1411 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1412 strpos($text, '[') !== false
1415 $text .= ']'; # so that replaceExternalLinks($text) works later
1418 # fix up urlencoded title texts
1419 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1421 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1422 $might_be_img = true;
1424 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1426 } else { # Invalid form; output directly
1427 $s .= $prefix . '[[' . $line ;
1431 # Don't allow internal links to pages containing
1432 # PROTO: where PROTO is a valid URL protocol; these
1433 # should be external links.
1434 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1435 $s .= $prefix . '[[' . $line ;
1439 # Make subpage if necessary
1440 if( $useSubpages ) {
1441 $link = $this->maybeDoSubpageLink( $m[1], $text );
1446 $noforce = (substr($m[1], 0, 1) != ':');
1448 # Strip off leading ':'
1449 $link = substr($link, 1);
1452 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1454 $s .= $prefix . '[[' . $line;
1458 #check other language variants of the link
1459 #if the article does not exist
1460 if( $checkVariantLink
1461 && $nt->getArticleID() == 0 ) {
1462 $wgContLang->findVariantLink($link, $nt);
1465 $ns = $nt->getNamespace();
1466 $iw = $nt->getInterWiki();
1468 if ($might_be_img) { # if this is actually an invalid link
1469 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1471 while (isset ($a[$k+
1]) ) {
1472 #look at the next 'line' to see if we can close it there
1473 $spliced = array_splice( $a, $k +
1, 1 );
1474 $next_line = array_shift( $spliced );
1475 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1476 # the first ]] closes the inner link, the second the image
1478 $text .= '[[' . $m[1];
1481 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1482 #if there's exactly one ]] that's fine, we'll keep looking
1483 $text .= '[[' . $m[0];
1485 #if $next_line is invalid too, we need look no further
1486 $text .= '[[' . $next_line;
1491 # we couldn't find the end of this imageLink, so output it raw
1492 #but don't ignore what might be perfectly normal links in the text we've examined
1493 $text = $this->replaceInternalLinks($text);
1494 $s .= $prefix . '[[' . $link . '|' . $text;
1495 # note: no $trail, because without an end, there *is* no trail
1498 } else { #it's not an image, so output it raw
1499 $s .= $prefix . '[[' . $link . '|' . $text;
1500 # note: no $trail, because without an end, there *is* no trail
1505 $wasblank = ( '' == $text );
1506 if( $wasblank ) $text = $link;
1509 # Link not escaped by : , create the various objects
1513 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1514 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1515 $s = rtrim($s . "\n");
1516 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1520 if ( $ns == NS_IMAGE
) {
1521 wfProfileIn( "$fname-image" );
1522 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1523 # recursively parse links inside the image caption
1524 # actually, this will parse them in any other parameters, too,
1525 # but it might be hard to fix that, and it doesn't matter ATM
1526 $text = $this->replaceExternalLinks($text);
1527 $text = $this->replaceInternalLinks($text);
1529 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1530 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1531 $this->mOutput
->addImage( $nt->getDBkey() );
1533 wfProfileOut( "$fname-image" );
1536 wfProfileOut( "$fname-image" );
1540 if ( $ns == NS_CATEGORY
) {
1541 wfProfileIn( "$fname-category" );
1542 $s = rtrim($s . "\n"); # bug 87
1545 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1546 $sortkey = $this->mTitle
->getText();
1548 $sortkey = $this->mTitle
->getPrefixedText();
1553 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1554 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1555 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1558 * Strip the whitespace Category links produce, see bug 87
1559 * @todo We might want to use trim($tmp, "\n") here.
1561 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1563 wfProfileOut( "$fname-category" );
1568 if( ( $nt->getPrefixedText() === $selflink ) &&
1569 ( $nt->getFragment() === '' ) ) {
1570 # Self-links are handled specially; generally de-link and change to bold.
1571 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1575 # Special and Media are pseudo-namespaces; no pages actually exist in them
1576 if( $ns == NS_MEDIA
) {
1577 $link = $sk->makeMediaLinkObj( $nt, $text );
1578 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1579 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1580 $this->mOutput
->addImage( $nt->getDBkey() );
1582 } elseif( $ns == NS_SPECIAL
) {
1583 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1585 } elseif( $ns == NS_IMAGE
) {
1586 $img = Image
::newFromTitle( $nt );
1587 if( $img->exists() ) {
1588 // Force a blue link if the file exists; may be a remote
1589 // upload on the shared repository, and we want to see its
1590 // auto-generated page.
1591 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1595 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1597 wfProfileOut( $fname );
1602 * Make a link placeholder. The text returned can be later resolved to a real link with
1603 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1604 * parsing of interwiki links, and secondly to allow all extistence checks and
1605 * article length checks (for stub links) to be bundled into a single query.
1608 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1609 if ( ! is_object($nt) ) {
1611 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1613 # Separate the link trail from the rest of the link
1614 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1616 if ( $nt->isExternal() ) {
1617 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1618 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1619 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1621 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1622 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1623 $this->mLinkHolders
['queries'][] = $query;
1624 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1625 $this->mLinkHolders
['titles'][] = $nt;
1627 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1634 * Render a forced-blue link inline; protect against double expansion of
1635 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1636 * Since this little disaster has to split off the trail text to avoid
1637 * breaking URLs in the following text without breaking trails on the
1638 * wiki links, it's been made into a horrible function.
1641 * @param string $text
1642 * @param string $query
1643 * @param string $trail
1644 * @param string $prefix
1645 * @return string HTML-wikitext mix oh yuck
1647 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1648 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1649 $sk =& $this->mOptions
->getSkin();
1650 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1651 return $this->armorLinks( $link ) . $trail;
1655 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1656 * going to go through further parsing steps before inline URL expansion.
1658 * In particular this is important when using action=render, which causes
1659 * full URLs to be included.
1661 * Oh man I hate our multi-layer parser!
1663 * @param string more-or-less HTML
1664 * @return string less-or-more HTML with NOPARSE bits
1666 function armorLinks( $text ) {
1667 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1668 "{$this->mUniqPrefix}NOPARSE$1", $text );
1672 * Return true if subpage links should be expanded on this page.
1675 function areSubpagesAllowed() {
1676 # Some namespaces don't allow subpages
1677 global $wgNamespacesWithSubpages;
1678 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1682 * Handle link to subpage if necessary
1683 * @param string $target the source of the link
1684 * @param string &$text the link text, modified as necessary
1685 * @return string the full name of the link
1688 function maybeDoSubpageLink($target, &$text) {
1691 # :Foobar -- override special treatment of prefix (images, language links)
1692 # /Foobar -- convert to CurrentPage/Foobar
1693 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1694 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1695 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1697 $fname = 'Parser::maybeDoSubpageLink';
1698 wfProfileIn( $fname );
1699 $ret = $target; # default return value is no change
1701 # Some namespaces don't allow subpages,
1702 # so only perform processing if subpages are allowed
1703 if( $this->areSubpagesAllowed() ) {
1704 # Look at the first character
1705 if( $target != '' && $target{0} == '/' ) {
1706 # / at end means we don't want the slash to be shown
1707 if( substr( $target, -1, 1 ) == '/' ) {
1708 $target = substr( $target, 1, -1 );
1711 $noslash = substr( $target, 1 );
1714 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1715 if( '' === $text ) {
1717 } # this might be changed for ugliness reasons
1719 # check for .. subpage backlinks
1721 $nodotdot = $target;
1722 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1724 $nodotdot = substr( $nodotdot, 3 );
1726 if($dotdotcount > 0) {
1727 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1728 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1729 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1730 # / at the end means don't show full path
1731 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1732 $nodotdot = substr( $nodotdot, 0, -1 );
1733 if( '' === $text ) {
1737 $nodotdot = trim( $nodotdot );
1738 if( $nodotdot != '' ) {
1739 $ret .= '/' . $nodotdot;
1746 wfProfileOut( $fname );
1751 * Used by doBlockLevels()
1754 /* private */ function closeParagraph() {
1756 if ( '' != $this->mLastSection
) {
1757 $result = '</' . $this->mLastSection
. ">\n";
1759 $this->mInPre
= false;
1760 $this->mLastSection
= '';
1763 # getCommon() returns the length of the longest common substring
1764 # of both arguments, starting at the beginning of both.
1766 /* private */ function getCommon( $st1, $st2 ) {
1767 $fl = strlen( $st1 );
1768 $shorter = strlen( $st2 );
1769 if ( $fl < $shorter ) { $shorter = $fl; }
1771 for ( $i = 0; $i < $shorter; ++
$i ) {
1772 if ( $st1{$i} != $st2{$i} ) { break; }
1776 # These next three functions open, continue, and close the list
1777 # element appropriate to the prefix character passed into them.
1779 /* private */ function openList( $char ) {
1780 $result = $this->closeParagraph();
1782 if ( '*' == $char ) { $result .= '<ul><li>'; }
1783 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1784 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1785 else if ( ';' == $char ) {
1786 $result .= '<dl><dt>';
1787 $this->mDTopen
= true;
1789 else { $result = '<!-- ERR 1 -->'; }
1794 /* private */ function nextItem( $char ) {
1795 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1796 else if ( ':' == $char ||
';' == $char ) {
1798 if ( $this->mDTopen
) { $close = '</dt>'; }
1799 if ( ';' == $char ) {
1800 $this->mDTopen
= true;
1801 return $close . '<dt>';
1803 $this->mDTopen
= false;
1804 return $close . '<dd>';
1807 return '<!-- ERR 2 -->';
1810 /* private */ function closeList( $char ) {
1811 if ( '*' == $char ) { $text = '</li></ul>'; }
1812 else if ( '#' == $char ) { $text = '</li></ol>'; }
1813 else if ( ':' == $char ) {
1814 if ( $this->mDTopen
) {
1815 $this->mDTopen
= false;
1816 $text = '</dt></dl>';
1818 $text = '</dd></dl>';
1821 else { return '<!-- ERR 3 -->'; }
1827 * Make lists from lines starting with ':', '*', '#', etc.
1830 * @return string the lists rendered as HTML
1832 function doBlockLevels( $text, $linestart ) {
1833 $fname = 'Parser::doBlockLevels';
1834 wfProfileIn( $fname );
1836 # Parsing through the text line by line. The main thing
1837 # happening here is handling of block-level elements p, pre,
1838 # and making lists from lines starting with * # : etc.
1840 $textLines = explode( "\n", $text );
1842 $lastPrefix = $output = '';
1843 $this->mDTopen
= $inBlockElem = false;
1845 $paragraphStack = false;
1847 if ( !$linestart ) {
1848 $output .= array_shift( $textLines );
1850 foreach ( $textLines as $oLine ) {
1851 $lastPrefixLength = strlen( $lastPrefix );
1852 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1853 $preOpenMatch = preg_match('/<pre/i', $oLine );
1854 if ( !$this->mInPre
) {
1855 # Multiple prefixes may abut each other for nested lists.
1856 $prefixLength = strspn( $oLine, '*#:;' );
1857 $pref = substr( $oLine, 0, $prefixLength );
1860 $pref2 = str_replace( ';', ':', $pref );
1861 $t = substr( $oLine, $prefixLength );
1862 $this->mInPre
= !empty($preOpenMatch);
1864 # Don't interpret any other prefixes in preformatted text
1866 $pref = $pref2 = '';
1871 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1872 # Same as the last item, so no need to deal with nesting or opening stuff
1873 $output .= $this->nextItem( substr( $pref, -1 ) );
1874 $paragraphStack = false;
1876 if ( substr( $pref, -1 ) == ';') {
1877 # The one nasty exception: definition lists work like this:
1878 # ; title : definition text
1879 # So we check for : in the remainder text to split up the
1880 # title and definition, without b0rking links.
1882 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1884 $output .= $term . $this->nextItem( ':' );
1887 } elseif( $prefixLength ||
$lastPrefixLength ) {
1888 # Either open or close a level...
1889 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1890 $paragraphStack = false;
1892 while( $commonPrefixLength < $lastPrefixLength ) {
1893 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1894 --$lastPrefixLength;
1896 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1897 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1899 while ( $prefixLength > $commonPrefixLength ) {
1900 $char = substr( $pref, $commonPrefixLength, 1 );
1901 $output .= $this->openList( $char );
1903 if ( ';' == $char ) {
1904 # FIXME: This is dupe of code above
1905 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1907 $output .= $term . $this->nextItem( ':' );
1910 ++
$commonPrefixLength;
1912 $lastPrefix = $pref2;
1914 if( 0 == $prefixLength ) {
1915 wfProfileIn( "$fname-paragraph" );
1916 # No prefix (not in list)--go to paragraph mode
1917 // XXX: use a stack for nestable elements like span, table and div
1918 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1919 $closematch = preg_match(
1920 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1921 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1922 if ( $openmatch or $closematch ) {
1923 $paragraphStack = false;
1924 $output .= $this->closeParagraph();
1925 if ( $preOpenMatch and !$preCloseMatch ) {
1926 $this->mInPre
= true;
1928 if ( $closematch ) {
1929 $inBlockElem = false;
1931 $inBlockElem = true;
1933 } else if ( !$inBlockElem && !$this->mInPre
) {
1934 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1936 if ($this->mLastSection
!= 'pre') {
1937 $paragraphStack = false;
1938 $output .= $this->closeParagraph().'<pre>';
1939 $this->mLastSection
= 'pre';
1941 $t = substr( $t, 1 );
1944 if ( '' == trim($t) ) {
1945 if ( $paragraphStack ) {
1946 $output .= $paragraphStack.'<br />';
1947 $paragraphStack = false;
1948 $this->mLastSection
= 'p';
1950 if ($this->mLastSection
!= 'p' ) {
1951 $output .= $this->closeParagraph();
1952 $this->mLastSection
= '';
1953 $paragraphStack = '<p>';
1955 $paragraphStack = '</p><p>';
1959 if ( $paragraphStack ) {
1960 $output .= $paragraphStack;
1961 $paragraphStack = false;
1962 $this->mLastSection
= 'p';
1963 } else if ($this->mLastSection
!= 'p') {
1964 $output .= $this->closeParagraph().'<p>';
1965 $this->mLastSection
= 'p';
1970 wfProfileOut( "$fname-paragraph" );
1972 // somewhere above we forget to get out of pre block (bug 785)
1973 if($preCloseMatch && $this->mInPre
) {
1974 $this->mInPre
= false;
1976 if ($paragraphStack === false) {
1980 while ( $prefixLength ) {
1981 $output .= $this->closeList( $pref2{$prefixLength-1} );
1984 if ( '' != $this->mLastSection
) {
1985 $output .= '</' . $this->mLastSection
. '>';
1986 $this->mLastSection
= '';
1989 wfProfileOut( $fname );
1994 * Split up a string on ':', ignoring any occurences inside
1995 * <a>..</a> or <span>...</span>
1996 * @param string $str the string to split
1997 * @param string &$before set to everything before the ':'
1998 * @param string &$after set to everything after the ':'
1999 * return string the position of the ':', or false if none found
2001 function findColonNoLinks($str, &$before, &$after) {
2002 # I wonder if we should make this count all tags, not just <a>
2003 # and <span>. That would prevent us from matching a ':' that
2004 # comes in the middle of italics other such formatting....
2006 $fname = 'Parser::findColonNoLinks';
2007 wfProfileIn( $fname );
2010 $colon = strpos($str, ':', $pos);
2012 if ($colon !== false) {
2013 $before = substr($str, 0, $colon);
2014 $after = substr($str, $colon +
1);
2016 # Skip any ':' within <a> or <span> pairs
2017 $a = substr_count($before, '<a');
2018 $s = substr_count($before, '<span');
2019 $ca = substr_count($before, '</a>');
2020 $cs = substr_count($before, '</span>');
2022 if ($a <= $ca and $s <= $cs) {
2023 # Tags are balanced before ':'; ok
2028 } while ($colon !== false);
2029 wfProfileOut( $fname );
2034 * Return value of a magic variable (like PAGENAME)
2038 function getVariableValue( $index ) {
2039 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2042 * Some of these require message or data lookups and can be
2043 * expensive to check many times.
2045 static $varCache = array();
2046 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2047 if ( isset( $varCache[$index] ) )
2048 return $varCache[$index];
2051 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2054 case MAG_CURRENTMONTH
:
2055 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2056 case MAG_CURRENTMONTHNAME
:
2057 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2058 case MAG_CURRENTMONTHNAMEGEN
:
2059 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2060 case MAG_CURRENTMONTHABBREV
:
2061 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2062 case MAG_CURRENTDAY
:
2063 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2064 case MAG_CURRENTDAY2
:
2065 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2067 return $this->mTitle
->getText();
2069 return $this->mTitle
->getPartialURL();
2070 case MAG_FULLPAGENAME
:
2071 return $this->mTitle
->getPrefixedText();
2072 case MAG_FULLPAGENAMEE
:
2073 return $this->mTitle
->getPrefixedURL();
2074 case MAG_SUBPAGENAME
:
2075 return $this->mTitle
->getSubpageText();
2076 case MAG_REVISIONID
:
2077 return $this->mRevisionId
;
2079 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2080 case MAG_NAMESPACEE
:
2081 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2082 case MAG_CURRENTDAYNAME
:
2083 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2084 case MAG_CURRENTYEAR
:
2085 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2086 case MAG_CURRENTTIME
:
2087 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2088 case MAG_CURRENTWEEK
:
2089 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2090 // int to remove the padding
2091 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2092 case MAG_CURRENTDOW
:
2093 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2094 case MAG_NUMBEROFARTICLES
:
2095 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2096 case MAG_NUMBEROFFILES
:
2097 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2102 case MAG_SERVERNAME
:
2103 return $wgServerName;
2104 case MAG_SCRIPTPATH
:
2105 return $wgScriptPath;
2108 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2116 * initialise the magic variables (like CURRENTMONTHNAME)
2120 function initialiseVariables() {
2121 $fname = 'Parser::initialiseVariables';
2122 wfProfileIn( $fname );
2123 global $wgVariableIDs;
2124 $this->mVariables
= array();
2125 foreach ( $wgVariableIDs as $id ) {
2126 $mw =& MagicWord
::get( $id );
2127 $mw->addToArray( $this->mVariables
, $id );
2129 wfProfileOut( $fname );
2133 * parse any parentheses in format ((title|part|part))
2134 * and call callbacks to get a replacement text for any found piece
2136 * @param string $text The text to parse
2137 * @param array $callbacks rules in form:
2138 * '{' => array( # opening parentheses
2139 * 'end' => '}', # closing parentheses
2140 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2141 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2146 function replace_callback ($text, $callbacks) {
2147 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2148 $lastOpeningBrace = -1; # last not closed parentheses
2150 for ($i = 0; $i < strlen($text); $i++
) {
2151 # check for any opening brace
2154 foreach ($callbacks as $key => $value) {
2155 $pos = strpos ($text, $key, $i);
2156 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2162 if ($lastOpeningBrace >= 0) {
2163 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2165 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2170 $pos = strpos ($text, '|', $i);
2172 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2183 # found openning brace, lets add it to parentheses stack
2184 if (null != $rule) {
2185 $piece = array('brace' => $text[$i],
2186 'braceEnd' => $rule['end'],
2191 # count openning brace characters
2192 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2197 $piece['startAt'] = $i+
1;
2198 $piece['partStart'] = $i+
1;
2200 # we need to add to stack only if openning brace count is enough for any given rule
2201 foreach ($rule['cb'] as $cnt => $fn) {
2202 if ($piece['count'] >= $cnt) {
2203 $lastOpeningBrace ++
;
2204 $openingBraceStack[$lastOpeningBrace] = $piece;
2211 else if ($lastOpeningBrace >= 0) {
2212 # first check if it is a closing brace
2213 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2214 # lets check if it is enough characters for closing brace
2216 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2219 # if there are more closing parentheses than opening ones, we parse less
2220 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2221 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2223 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2225 $matchingCallback = null;
2226 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2227 if ($count >= $cnt && $matchingCount < $cnt) {
2228 $matchingCount = $cnt;
2229 $matchingCallback = $fn;
2233 if ($matchingCount == 0) {
2238 # lets set a title or last part (if '|' was found)
2239 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2240 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2242 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2244 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2245 $pieceEnd = $i +
$matchingCount;
2247 if( is_callable( $matchingCallback ) ) {
2249 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2250 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2251 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2252 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2254 # finally we can call a user callback and replace piece of text
2255 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2256 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2257 $i = $pieceStart +
strlen($replaceWith) - 1;
2260 # null value for callback means that parentheses should be parsed, but not replaced
2261 $i +
= $matchingCount - 1;
2264 # reset last openning parentheses, but keep it in case there are unused characters
2265 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2266 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2267 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2270 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2271 $openingBraceStack[$lastOpeningBrace--] = null;
2273 if ($matchingCount < $piece['count']) {
2274 $piece['count'] -= $matchingCount;
2275 $piece['startAt'] -= $matchingCount;
2276 $piece['partStart'] = $piece['startAt'];
2277 # do we still qualify for any callback with remaining count?
2278 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2279 if ($piece['count'] >= $cnt) {
2280 $lastOpeningBrace ++
;
2281 $openingBraceStack[$lastOpeningBrace] = $piece;
2289 # lets set a title if it is a first separator, or next part otherwise
2290 if ($text[$i] == '|') {
2291 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2292 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2293 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2296 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2298 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2307 * Replace magic variables, templates, and template arguments
2308 * with the appropriate text. Templates are substituted recursively,
2309 * taking care to avoid infinite loops.
2311 * Note that the substitution depends on value of $mOutputType:
2312 * OT_WIKI: only {{subst:}} templates
2313 * OT_MSG: only magic variables
2314 * OT_HTML: all templates and magic variables
2316 * @param string $tex The text to transform
2317 * @param array $args Key-value pairs representing template parameters to substitute
2318 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2321 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2322 # Prevent too big inclusions
2323 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2327 $fname = 'Parser::replaceVariables';
2328 wfProfileIn( $fname );
2330 # This function is called recursively. To keep track of arguments we need a stack:
2331 array_push( $this->mArgStack
, $args );
2333 $braceCallbacks = array();
2335 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2337 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2338 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2340 $callbacks = array();
2341 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2342 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2343 $text = $this->replace_callback ($text, $callbacks);
2345 array_pop( $this->mArgStack
);
2347 wfProfileOut( $fname );
2352 * Replace magic variables
2355 function variableSubstitution( $matches ) {
2356 $fname = 'Parser::variableSubstitution';
2357 $varname = $matches[1];
2358 wfProfileIn( $fname );
2359 if ( !$this->mVariables
) {
2360 $this->initialiseVariables();
2363 if ( $this->mOutputType
== OT_WIKI
) {
2364 # Do only magic variables prefixed by SUBST
2365 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2366 if (!$mwSubst->matchStartAndRemove( $varname ))
2368 # Note that if we don't substitute the variable below,
2369 # we don't remove the {{subst:}} magic word, in case
2370 # it is a template rather than a magic variable.
2372 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2373 $id = $this->mVariables
[$varname];
2374 $text = $this->getVariableValue( $id );
2375 $this->mOutput
->mContainsOldMagic
= true;
2377 $text = $matches[0];
2379 wfProfileOut( $fname );
2383 # Split template arguments
2384 function getTemplateArgs( $argsString ) {
2385 if ( $argsString === '' ) {
2389 $args = explode( '|', substr( $argsString, 1 ) );
2391 # If any of the arguments contains a '[[' but no ']]', it needs to be
2392 # merged with the next arg because the '|' character between belongs
2393 # to the link syntax and not the template parameter syntax.
2394 $argc = count($args);
2396 for ( $i = 0; $i < $argc-1; $i++
) {
2397 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2398 $args[$i] .= '|'.$args[$i+
1];
2399 array_splice($args, $i+
1, 1);
2409 * Return the text of a template, after recursively
2410 * replacing any variables or templates within the template.
2412 * @param array $piece The parts of the template
2413 * $piece['text']: matched text
2414 * $piece['title']: the title, i.e. the part before the |
2415 * $piece['parts']: the parameter array
2416 * @return string the text of the template
2419 function braceSubstitution( $piece ) {
2421 $fname = 'Parser::braceSubstitution';
2422 wfProfileIn( $fname );
2425 $found = false; # $text has been filled
2426 $nowiki = false; # wiki markup in $text should be escaped
2427 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2428 $noargs = false; # Don't replace triple-brace arguments in $text
2429 $replaceHeadings = false; # Make the edit section links go to the template not the article
2430 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2431 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2433 # Title object, where $text came from
2438 # $part1 is the bit before the first |, and must contain only title characters
2439 # $args is a list of arguments, starting from index 0, not including $part1
2441 $part1 = $piece['title'];
2442 # If the third subpattern matched anything, it will start with |
2444 if (null == $piece['parts']) {
2445 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2446 if ($replaceWith != $piece['text']) {
2447 $text = $replaceWith;
2454 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2455 $argc = count( $args );
2459 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2460 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2461 # One of two possibilities is true:
2462 # 1) Found SUBST but not in the PST phase
2463 # 2) Didn't find SUBST and in the PST phase
2464 # In either case, return without further processing
2465 $text = $piece['text'];
2472 # MSG, MSGNW, INT and RAW
2475 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2476 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2479 # Remove obsolete MSG:
2480 $mwMsg =& MagicWord
::get( MAG_MSG
);
2481 $mwMsg->matchStartAndRemove( $part1 );
2485 $mwRaw =& MagicWord
::get( MAG_RAW
);
2486 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2487 $forceRawInterwiki = true;
2490 # Check if it is an internal message
2491 $mwInt =& MagicWord
::get( MAG_INT
);
2492 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2493 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2494 $text = $linestart . wfMsgReal( $part1, $args, true );
2502 # Check for NS: (namespace expansion)
2503 $mwNs = MagicWord
::get( MAG_NS
);
2504 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2505 if ( intval( $part1 ) ||
$part1 == "0" ) {
2506 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2509 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2510 if ( !is_null( $index ) ) {
2511 $text = $linestart . $wgContLang->getNsText( $index );
2518 # LCFIRST, UCFIRST, LC and UC
2520 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2521 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2522 $lc =& MagicWord
::get( MAG_LC
);
2523 $uc =& MagicWord
::get( MAG_UC
);
2524 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2525 $text = $linestart . $wgContLang->lcfirst( $part1 );
2527 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2528 $text = $linestart . $wgContLang->ucfirst( $part1 );
2530 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2531 $text = $linestart . $wgContLang->lc( $part1 );
2533 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2534 $text = $linestart . $wgContLang->uc( $part1 );
2539 # LOCALURL and FULLURL
2541 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2542 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2543 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2544 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2547 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2548 $func = 'getLocalURL';
2549 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2550 $func = 'escapeLocalURL';
2551 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2552 $func = 'getFullURL';
2553 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2554 $func = 'escapeFullURL';
2559 if ( $func !== false ) {
2560 $title = Title
::newFromText( $part1 );
2561 if ( !is_null( $title ) ) {
2563 $text = $linestart . $title->$func( $args[0] );
2565 $text = $linestart . $title->$func();
2573 if ( !$found && $argc == 1 ) {
2574 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2575 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2576 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2582 if ( !$found && $argc >= 2 ) {
2583 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2584 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2585 if ($argc==2) {$args[2]=$args[1];}
2586 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2591 # Template table test
2593 # Did we encounter this template already? If yes, it is in the cache
2594 # and we need to check for loops.
2595 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2598 # Infinite loop test
2599 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2603 $text = $linestart .
2604 '{{' . $part1 . '}}' .
2605 '<!-- WARNING: template loop detected -->';
2606 wfDebug( "$fname: template loop broken at '$part1'\n" );
2608 # set $text to cached message.
2609 $text = $linestart . $this->mTemplates
[$piece['title']];
2613 # Load from database
2614 $lastPathLevel = $this->mTemplatePath
;
2617 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2618 if ($subpage !== '') {
2619 $ns = $this->mTitle
->getNamespace();
2621 $title = Title
::newFromText( $part1, $ns );
2623 if ( !is_null( $title ) ) {
2624 if ( !$title->isExternal() ) {
2625 # Check for excessive inclusion
2626 $dbk = $title->getPrefixedDBkey();
2627 if ( $this->incrementIncludeCount( $dbk ) ) {
2628 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2629 # Capture special page output
2630 $text = SpecialPage
::capturePath( $title );
2631 if ( is_string( $text ) ) {
2636 $this->disableCache();
2639 $articleContent = $this->fetchTemplate( $title );
2640 if ( $articleContent !== false ) {
2642 $text = $articleContent;
2643 $replaceHeadings = true;
2648 # If the title is valid but undisplayable, make a link to it
2649 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2650 $text = '[['.$title->getPrefixedText().']]';
2653 } elseif ( $title->isTrans() ) {
2654 // Interwiki transclusion
2655 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2656 $text = $this->interwikiTransclude( $title, 'render' );
2660 $text = $this->interwikiTransclude( $title, 'raw' );
2661 $replaceHeadings = true;
2666 # Template cache array insertion
2667 # Use the original $piece['title'] not the mangled $part1, so that
2668 # modifiers such as RAW: produce separate cache entries
2670 $this->mTemplates
[$piece['title']] = $text;
2671 $text = $linestart . $text;
2676 # Recursive parsing, escaping and link table handling
2677 # Only for HTML output
2678 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2679 $text = wfEscapeWikiText( $text );
2680 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2682 # Clean up argument array
2683 $assocArgs = array();
2685 foreach( $args as $arg ) {
2686 $eqpos = strpos( $arg, '=' );
2687 if ( $eqpos === false ) {
2688 $assocArgs[$index++
] = $arg;
2690 $name = trim( substr( $arg, 0, $eqpos ) );
2691 $value = trim( substr( $arg, $eqpos+
1 ) );
2692 if ( $value === false ) {
2695 if ( $name !== false ) {
2696 $assocArgs[$name] = $value;
2701 # Add a new element to the templace recursion path
2702 $this->mTemplatePath
[$part1] = 1;
2706 # If there are any <onlyinclude> tags, only include them
2707 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2708 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2710 foreach ($m[1] as $piece)
2713 # Remove <noinclude> sections and <includeonly> tags
2714 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2715 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2717 if( $this->mOutputType
== OT_HTML
) {
2718 # Strip <nowiki>, <pre>, etc.
2719 $text = $this->strip( $text, $this->mStripState
);
2720 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2722 $text = $this->replaceVariables( $text, $assocArgs );
2724 # If the template begins with a table or block-level
2725 # element, it should be treated as beginning a new line.
2726 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2727 $text = "\n" . $text;
2729 } elseif ( !$noargs ) {
2730 # $noparse and !$noargs
2731 # Just replace the arguments, not any double-brace items
2732 # This is used for rendered interwiki transclusion
2733 $text = $this->replaceVariables( $text, $assocArgs, true );
2736 # Prune lower levels off the recursion check path
2737 $this->mTemplatePath
= $lastPathLevel;
2740 wfProfileOut( $fname );
2741 return $piece['text'];
2744 # Replace raw HTML by a placeholder
2745 # Add a blank line preceding, to prevent it from mucking up
2746 # immediately preceding headings
2747 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2749 # replace ==section headers==
2750 # XXX this needs to go away once we have a better parser.
2751 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2752 if( !is_null( $title ) )
2753 $encodedname = base64_encode($title->getPrefixedDBkey());
2755 $encodedname = base64_encode("");
2756 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2757 PREG_SPLIT_DELIM_CAPTURE
);
2760 for( $i = 0; $i < count($m); $i +
= 2 ) {
2762 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2764 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2768 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2769 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2770 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2778 # Prune lower levels off the recursion check path
2779 $this->mTemplatePath
= $lastPathLevel;
2782 wfProfileOut( $fname );
2783 return $piece['text'];
2785 wfProfileOut( $fname );
2791 * Fetch the unparsed text of a template and register a reference to it.
2793 function fetchTemplate( $title ) {
2795 // Loop to fetch the article, with up to 1 redirect
2796 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2797 $rev = Revision
::newFromTitle( $title );
2798 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2802 $text = $rev->getText();
2803 if ( $text === false ) {
2807 $title = Title
::newFromRedirect( $text );
2813 * Transclude an interwiki link.
2815 function interwikiTransclude( $title, $action ) {
2816 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2818 if (!$wgEnableScaryTranscluding)
2819 return wfMsg('scarytranscludedisabled');
2821 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2822 // But we'll handle it generally anyway
2823 if ( $title->getNamespace() ) {
2824 // Use the canonical namespace, which should work anywhere
2825 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2827 $articleName = $title->getDBkey();
2830 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2831 $url .= "?action=$action";
2832 if (strlen($url) > 255)
2833 return wfMsg('scarytranscludetoolong');
2834 return $this->fetchScaryTemplateMaybeFromCache($url);
2837 function fetchScaryTemplateMaybeFromCache($url) {
2838 global $wgTranscludeCacheExpiry;
2839 $dbr =& wfGetDB(DB_SLAVE
);
2840 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2841 array('tc_url' => $url));
2843 $time = $obj->tc_time
;
2844 $text = $obj->tc_contents
;
2845 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2850 $text = wfGetHTTP($url);
2852 return wfMsg('scarytranscludefailed', $url);
2854 $dbw =& wfGetDB(DB_MASTER
);
2855 $dbw->replace('transcache', array('tc_url'), array(
2857 'tc_time' => time(),
2858 'tc_contents' => $text));
2864 * Triple brace replacement -- used for template arguments
2867 function argSubstitution( $matches ) {
2868 $arg = trim( $matches['title'] );
2869 $text = $matches['text'];
2870 $inputArgs = end( $this->mArgStack
);
2872 if ( array_key_exists( $arg, $inputArgs ) ) {
2873 $text = $inputArgs[$arg];
2874 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2875 $text = $matches['parts'][0];
2882 * Returns true if the function is allowed to include this entity
2885 function incrementIncludeCount( $dbk ) {
2886 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2887 $this->mIncludeCount
[$dbk] = 0;
2889 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2897 * This function accomplishes several tasks:
2898 * 1) Auto-number headings if that option is enabled
2899 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2900 * 3) Add a Table of contents on the top for users who have enabled the option
2901 * 4) Auto-anchor headings
2903 * It loops through all headlines, collects the necessary data, then splits up the
2904 * string and re-inserts the newly formatted headlines.
2906 * @param string $text
2907 * @param boolean $isMain
2910 function formatHeadings( $text, $isMain=true ) {
2911 global $wgMaxTocLevel, $wgContLang;
2913 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2915 $forceTocHere = false;
2916 if( !$this->mTitle
->userCanEdit() ) {
2919 $showEditLink = $this->mOptions
->getEditSection();
2922 # Inhibit editsection links if requested in the page
2923 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2924 if( $esw->matchAndRemove( $text ) ) {
2927 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2929 $mw =& MagicWord
::get( MAG_NOTOC
);
2930 if( $mw->matchAndRemove( $text ) ) {
2934 # Get all headlines for numbering them and adding funky stuff like [edit]
2935 # links - this is for later, but we need the number of headlines right now
2936 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2938 # if there are fewer than 4 headlines in the article, do not show TOC
2939 if( $numMatches < 4 ) {
2943 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2944 # override above conditions and always show TOC at that place
2946 $mw =& MagicWord
::get( MAG_TOC
);
2947 if($mw->match( $text ) ) {
2949 $forceTocHere = true;
2951 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2952 # override above conditions and always show TOC above first header
2953 $mw =& MagicWord
::get( MAG_FORCETOC
);
2954 if ($mw->matchAndRemove( $text ) ) {
2959 # Never ever show TOC if no headers
2960 if( $numMatches < 1 ) {
2964 # We need this to perform operations on the HTML
2965 $sk =& $this->mOptions
->getSkin();
2969 $sectionCount = 0; # headlineCount excluding template sections
2971 # Ugh .. the TOC should have neat indentation levels which can be
2972 # passed to the skin functions. These are determined here
2976 $sublevelCount = array();
2977 $levelCount = array();
2984 foreach( $matches[3] as $headline ) {
2986 $templatetitle = '';
2987 $templatesection = 0;
2990 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2992 $templatetitle = base64_decode($mat[1]);
2993 $templatesection = 1 +
(int)base64_decode($mat[2]);
2994 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2998 $prevlevel = $level;
2999 $prevtoclevel = $toclevel;
3001 $level = $matches[1][$headlineCount];
3003 if( $doNumberHeadings ||
$doShowToc ) {
3005 if ( $level > $prevlevel ) {
3006 # Increase TOC level
3008 $sublevelCount[$toclevel] = 0;
3009 $toc .= $sk->tocIndent();
3011 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3012 # Decrease TOC level, find level to jump to
3014 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3015 # Can only go down to level 1
3018 for ($i = $toclevel; $i > 0; $i--) {
3019 if ( $levelCount[$i] == $level ) {
3020 # Found last matching level
3024 elseif ( $levelCount[$i] < $level ) {
3025 # Found first matching level below current level
3032 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3035 # No change in level, end TOC line
3036 $toc .= $sk->tocLineEnd();
3039 $levelCount[$toclevel] = $level;
3041 # count number of headlines for each level
3042 @$sublevelCount[$toclevel]++
;
3044 for( $i = 1; $i <= $toclevel; $i++
) {
3045 if( !empty( $sublevelCount[$i] ) ) {
3049 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3055 # The canonized header is a version of the header text safe to use for links
3056 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3057 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3058 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3060 # Remove link placeholders by the link text.
3061 # <!--LINK number-->
3063 # link text with suffix
3064 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3065 "\$this->mLinkHolders['texts'][\$1]",
3066 $canonized_headline );
3067 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3068 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3069 $canonized_headline );
3072 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3073 $tocline = trim( $canonized_headline );
3074 # Save headline for section edit hint before it's escaped
3075 $headline_hint = trim( $canonized_headline );
3076 $canonized_headline = Sanitizer
::escapeId( $tocline );
3077 $refers[$headlineCount] = $canonized_headline;
3079 # count how many in assoc. array so we can track dupes in anchors
3080 @$refers[$canonized_headline]++
;
3081 $refcount[$headlineCount]=$refers[$canonized_headline];
3083 # Don't number the heading if it is the only one (looks silly)
3084 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3085 # the two are different if the line contains a link
3086 $headline=$numbering . ' ' . $headline;
3089 # Create the anchor for linking from the TOC to the section
3090 $anchor = $canonized_headline;
3091 if($refcount[$headlineCount] > 1 ) {
3092 $anchor .= '_' . $refcount[$headlineCount];
3094 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3095 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3097 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3098 if ( empty( $head[$headlineCount] ) ) {
3099 $head[$headlineCount] = '';
3102 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3104 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3107 # give headline the correct <h#> tag
3108 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3116 $toc .= $sk->tocUnindent( $toclevel - 1 );
3117 $toc = $sk->tocList( $toc );
3120 # split up and insert constructed headlines
3122 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3125 foreach( $blocks as $block ) {
3126 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3127 # This is the [edit] link that appears for the top block of text when
3128 # section editing is enabled
3130 # Disabled because it broke block formatting
3131 # For example, a bullet point in the top line
3132 # $full .= $sk->editSectionLink(0);
3135 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3136 # Top anchor now in skin
3140 if( !empty( $head[$i] ) ) {
3146 $mw =& MagicWord
::get( MAG_TOC
);
3147 return $mw->replace( $toc, $full );
3154 * Return an HTML link for the "ISBN 123456" text
3157 function magicISBN( $text ) {
3158 $fname = 'Parser::magicISBN';
3159 wfProfileIn( $fname );
3161 $a = split( 'ISBN ', ' '.$text );
3162 if ( count ( $a ) < 2 ) {
3163 wfProfileOut( $fname );
3166 $text = substr( array_shift( $a ), 1);
3167 $valid = '0123456789-Xx';
3169 foreach ( $a as $x ) {
3170 $isbn = $blank = '' ;
3171 while ( ' ' == $x{0} ) {
3173 $x = substr( $x, 1 );
3175 if ( $x == '' ) { # blank isbn
3176 $text .= "ISBN $blank";
3179 while ( strstr( $valid, $x{0} ) != false ) {
3181 $x = substr( $x, 1 );
3183 $num = str_replace( '-', '', $isbn );
3184 $num = str_replace( ' ', '', $num );
3185 $num = str_replace( 'x', 'X', $num );
3188 $text .= "ISBN $blank$x";
3190 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3191 $text .= '<a href="' .
3192 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3193 "\" class=\"internal\">ISBN $isbn</a>";
3197 wfProfileOut( $fname );
3202 * Return an HTML link for the "RFC 1234" text
3205 * @param string $text Text to be processed
3206 * @param string $keyword Magic keyword to use (default RFC)
3207 * @param string $urlmsg Interface message to use (default rfcurl)
3210 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3212 $valid = '0123456789';
3215 $a = split( $keyword, ' '.$text );
3216 if ( count ( $a ) < 2 ) {
3219 $text = substr( array_shift( $a ), 1);
3221 /* Check if keyword is preceed by [[.
3222 * This test is made here cause of the array_shift above
3223 * that prevent the test to be done in the foreach.
3225 if ( substr( $text, -2 ) == '[[' ) {
3229 foreach ( $a as $x ) {
3230 /* token might be empty if we have RFC RFC 1234 */
3238 /** remove and save whitespaces in $blank */
3239 while ( $x{0} == ' ' ) {
3241 $x = substr( $x, 1 );
3244 /** remove and save the rfc number in $id */
3245 while ( strstr( $valid, $x{0} ) != false ) {
3247 $x = substr( $x, 1 );
3251 /* call back stripped spaces*/
3252 $text .= $keyword.$blank.$x;
3253 } elseif( $internal ) {
3255 $text .= $keyword.$id.$x;
3257 /* build the external link*/
3258 $url = wfMsg( $urlmsg, $id);
3259 $sk =& $this->mOptions
->getSkin();
3260 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3261 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3264 /* Check if the next RFC keyword is preceed by [[ */
3265 $internal = ( substr($x,-2) == '[[' );
3271 * Transform wiki markup when saving a page by doing \r\n -> \n
3272 * conversion, substitting signatures, {{subst:}} templates, etc.
3274 * @param string $text the text to transform
3275 * @param Title &$title the Title object for the current article
3276 * @param User &$user the User object describing the current user
3277 * @param ParserOptions $options parsing options
3278 * @param bool $clearState whether to clear the parser state first
3279 * @return string the altered wiki markup
3282 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3283 $this->mOptions
= $options;
3284 $this->mTitle
=& $title;
3285 $this->mOutputType
= OT_WIKI
;
3287 if ( $clearState ) {
3288 $this->clearState();
3291 $stripState = false;
3295 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3296 $text = $this->strip( $text, $stripState, true );
3297 $text = $this->pstPass2( $text, $user );
3298 $text = $this->unstrip( $text, $stripState );
3299 $text = $this->unstripNoWiki( $text, $stripState );
3304 * Pre-save transform helper function
3307 function pstPass2( $text, &$user ) {
3308 global $wgContLang, $wgLocaltimezone;
3310 /* Note: This is the timestamp saved as hardcoded wikitext to
3311 * the database, we use $wgContLang here in order to give
3312 * everyone the same signiture and use the default one rather
3313 * than the one selected in each users preferences.
3315 if ( isset( $wgLocaltimezone ) ) {
3316 $oldtz = getenv( 'TZ' );
3317 putenv( 'TZ='.$wgLocaltimezone );
3319 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3320 ' (' . date( 'T' ) . ')';
3321 if ( isset( $wgLocaltimezone ) ) {
3322 putenv( 'TZ='.$oldtz );
3325 # Variable replacement
3326 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3327 $text = $this->replaceVariables( $text );
3330 $sigText = $this->getUserSig( $user );
3331 $text = strtr( $text, array(
3333 '~~~~' => "$sigText $d",
3337 # Context links: [[|name]] and [[name (context)|]]
3339 global $wgLegalTitleChars;
3340 $tc = "[$wgLegalTitleChars]";
3341 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3343 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3344 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3346 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3347 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3348 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3349 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3351 $t = $this->mTitle
->getText();
3352 if ( preg_match( $conpat, $t, $m ) ) {
3355 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3356 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3357 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3359 if ( '' == $context ) {
3360 $text = preg_replace( $p2, '[[\\1]]', $text );
3362 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3365 # Trim trailing whitespace
3366 # MAG_END (__END__) tag allows for trailing
3367 # whitespace to be deliberately included
3368 $text = rtrim( $text );
3369 $mw =& MagicWord
::get( MAG_END
);
3370 $mw->matchAndRemove( $text );
3376 * Fetch the user's signature text, if any, and normalize to
3377 * validated, ready-to-insert wikitext.
3383 function getUserSig( &$user ) {
3384 $username = $user->getName();
3385 $nickname = $user->getOption( 'nickname' );
3386 $nickname = $nickname === '' ?
$username : $nickname;
3388 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3389 # Sig. might contain markup; validate this
3390 if( $this->validateSig( $nickname ) !== false ) {
3391 # Validated; clean up (if needed) and return it
3392 return( $this->cleanSig( $nickname ) );
3394 # Failed to validate; fall back to the default
3395 $nickname = $username;
3396 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3400 # If we're still here, make it a link to the user page
3401 $userpage = $user->getUserPage();
3402 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3406 * Check that the user's signature contains no bad XML
3408 * @param string $text
3409 * @return mixed An expanded string, or false if invalid.
3411 function validateSig( $text ) {
3412 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3416 * Clean up signature text
3418 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3419 * 2) Substitute all transclusions
3421 * @param string $text
3422 * @return string Signature text
3424 function cleanSig( $text ) {
3425 $substWord = MagicWord
::get( MAG_SUBST
);
3426 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3427 $substText = '{{' . $substWord->getSynonym( 0 );
3429 $text = preg_replace( $substRegex, $substText, $text );
3430 $text = preg_replace( '/~{3,5}/', '', $text );
3431 $text = $this->replaceVariables( $text );
3437 * Set up some variables which are usually set up in parse()
3438 * so that an external function can call some class members with confidence
3441 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3442 $this->mTitle
=& $title;
3443 $this->mOptions
= $options;
3444 $this->mOutputType
= $outputType;
3445 if ( $clearState ) {
3446 $this->clearState();
3451 * Transform a MediaWiki message by replacing magic variables.
3453 * @param string $text the text to transform
3454 * @param ParserOptions $options options
3455 * @return string the text with variables substituted
3458 function transformMsg( $text, $options ) {
3460 static $executing = false;
3462 $fname = "Parser::transformMsg";
3464 # Guard against infinite recursion
3470 wfProfileIn($fname);
3472 $this->mTitle
= $wgTitle;
3473 $this->mOptions
= $options;
3474 $this->mOutputType
= OT_MSG
;
3475 $this->clearState();
3476 $text = $this->replaceVariables( $text );
3479 wfProfileOut($fname);
3484 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3485 * The callback should have the following form:
3486 * function myParserHook( $text, $params, &$parser ) { ... }
3488 * Transform and return $text. Use $parser for any required context, e.g. use
3489 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3493 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3494 * @param mixed $callback The callback function (and object) to use for the tag
3496 * @return The old value of the mTagHooks array associated with the hook
3498 function setHook( $tag, $callback ) {
3499 $oldVal = @$this->mTagHooks
[$tag];
3500 $this->mTagHooks
[$tag] = $callback;
3506 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3507 * Placeholders created in Skin::makeLinkObj()
3508 * Returns an array of links found, indexed by PDBK:
3512 * $options is a bit field, RLH_FOR_UPDATE to select for update
3514 function replaceLinkHolders( &$text, $options = 0 ) {
3516 global $wgOutputReplace;
3518 $fname = 'Parser::replaceLinkHolders';
3519 wfProfileIn( $fname );
3523 $sk =& $this->mOptions
->getSkin();
3524 $linkCache =& LinkCache
::singleton();
3526 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3527 wfProfileIn( $fname.'-check' );
3528 $dbr =& wfGetDB( DB_SLAVE
);
3529 $page = $dbr->tableName( 'page' );
3530 $threshold = $wgUser->getOption('stubthreshold');
3533 asort( $this->mLinkHolders
['namespaces'] );
3537 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3539 $title = $this->mLinkHolders
['titles'][$key];
3541 # Skip invalid entries.
3542 # Result will be ugly, but prevents crash.
3543 if ( is_null( $title ) ) {
3546 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3548 # Check if it's a static known link, e.g. interwiki
3549 if ( $title->isAlwaysKnown() ) {
3550 $colours[$pdbk] = 1;
3551 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3552 $colours[$pdbk] = 1;
3553 $this->mOutput
->addLink( $title, $id );
3554 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3555 $colours[$pdbk] = 0;
3557 # Not in the link cache, add it to the query
3558 if ( !isset( $current ) ) {
3560 $query = "SELECT page_id, page_namespace, page_title";
3561 if ( $threshold > 0 ) {
3562 $query .= ', page_len, page_is_redirect';
3564 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3565 } elseif ( $current != $ns ) {
3567 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3572 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3577 if ( $options & RLH_FOR_UPDATE
) {
3578 $query .= ' FOR UPDATE';
3581 $res = $dbr->query( $query, $fname );
3583 # Fetch data and form into an associative array
3584 # non-existent = broken
3587 while ( $s = $dbr->fetchObject($res) ) {
3588 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3589 $pdbk = $title->getPrefixedDBkey();
3590 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3591 $this->mOutput
->addLink( $title, $s->page_id
);
3593 if ( $threshold > 0 ) {
3594 $size = $s->page_len
;
3595 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3596 $colours[$pdbk] = 1;
3598 $colours[$pdbk] = 2;
3601 $colours[$pdbk] = 1;
3605 wfProfileOut( $fname.'-check' );
3607 # Construct search and replace arrays
3608 wfProfileIn( $fname.'-construct' );
3609 $wgOutputReplace = array();
3610 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3611 $pdbk = $pdbks[$key];
3612 $searchkey = "<!--LINK $key-->";
3613 $title = $this->mLinkHolders
['titles'][$key];
3614 if ( empty( $colours[$pdbk] ) ) {
3615 $linkCache->addBadLinkObj( $title );
3616 $colours[$pdbk] = 0;
3617 $this->mOutput
->addLink( $title, 0 );
3618 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3619 $this->mLinkHolders
['texts'][$key],
3620 $this->mLinkHolders
['queries'][$key] );
3621 } elseif ( $colours[$pdbk] == 1 ) {
3622 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3623 $this->mLinkHolders
['texts'][$key],
3624 $this->mLinkHolders
['queries'][$key] );
3625 } elseif ( $colours[$pdbk] == 2 ) {
3626 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3627 $this->mLinkHolders
['texts'][$key],
3628 $this->mLinkHolders
['queries'][$key] );
3631 wfProfileOut( $fname.'-construct' );
3634 wfProfileIn( $fname.'-replace' );
3636 $text = preg_replace_callback(
3637 '/(<!--LINK .*?-->)/',
3638 "wfOutputReplaceMatches",
3641 wfProfileOut( $fname.'-replace' );
3644 # Now process interwiki link holders
3645 # This is quite a bit simpler than internal links
3646 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3647 wfProfileIn( $fname.'-interwiki' );
3648 # Make interwiki link HTML
3649 $wgOutputReplace = array();
3650 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3651 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3652 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3655 $text = preg_replace_callback(
3656 '/<!--IWLINK (.*?)-->/',
3657 "wfOutputReplaceMatches",
3659 wfProfileOut( $fname.'-interwiki' );
3662 wfProfileOut( $fname );
3667 * Replace <!--LINK--> link placeholders with plain text of links
3668 * (not HTML-formatted).
3669 * @param string $text
3672 function replaceLinkHoldersText( $text ) {
3673 $fname = 'Parser::replaceLinkHoldersText';
3674 wfProfileIn( $fname );
3676 $text = preg_replace_callback(
3677 '/<!--(LINK|IWLINK) (.*?)-->/',
3678 array( &$this, 'replaceLinkHoldersTextCallback' ),
3681 wfProfileOut( $fname );
3686 * @param array $matches
3690 function replaceLinkHoldersTextCallback( $matches ) {
3691 $type = $matches[1];
3693 if( $type == 'LINK' ) {
3694 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3695 return $this->mLinkHolders
['texts'][$key];
3697 } elseif( $type == 'IWLINK' ) {
3698 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3699 return $this->mInterwikiLinkHolders
['texts'][$key];
3706 * Renders an image gallery from a text with one line per image.
3707 * text labels may be given by using |-style alternative text. E.g.
3708 * Image:one.jpg|The number "1"
3709 * Image:tree.jpg|A tree
3710 * given as text will return the HTML of a gallery with two images,
3711 * labeled 'The number "1"' and
3714 function renderImageGallery( $text ) {
3716 $parserOptions = new ParserOptions
;
3717 $localParser = new Parser();
3719 $ig = new ImageGallery();
3720 $ig->setShowBytes( false );
3721 $ig->setShowFilename( false );
3722 $lines = explode( "\n", $text );
3724 foreach ( $lines as $line ) {
3725 # match lines like these:
3726 # Image:someimage.jpg|This is some image
3727 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3729 if ( count( $matches ) == 0 ) {
3732 $nt =& Title
::newFromText( $matches[1] );
3733 if( is_null( $nt ) ) {
3734 # Bogus title. Ignore these so we don't bomb out later.
3737 if ( isset( $matches[3] ) ) {
3738 $label = $matches[3];
3743 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3744 $html = $pout->getText();
3746 $ig->add( new Image( $nt ), $html );
3747 $this->mOutput
->addImage( $nt->getDBkey() );
3749 return $ig->toHTML();
3753 * Parse image options text and use it to make an image
3755 function makeImage( &$nt, $options ) {
3756 global $wgUseImageResize;
3760 # Check if the options text is of the form "options|alt text"
3762 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3763 # * left no resizing, just left align. label is used for alt= only
3764 # * right same, but right aligned
3765 # * none same, but not aligned
3766 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3767 # * center center the image
3768 # * framed Keep original image size, no magnify-button.
3770 $part = explode( '|', $options);
3772 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3773 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3774 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3775 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3776 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3777 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3778 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3779 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3782 $width = $height = $framed = $thumb = false;
3783 $manual_thumb = '' ;
3785 foreach( $part as $key => $val ) {
3786 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3788 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3789 # use manually specified thumbnail
3791 $manual_thumb = $match;
3792 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3793 # remember to set an alignment, don't render immediately
3795 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3796 # remember to set an alignment, don't render immediately
3798 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3799 # remember to set an alignment, don't render immediately
3801 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3802 # remember to set an alignment, don't render immediately
3804 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3805 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3806 # $match is the image width in pixels
3807 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3808 $width = intval( $m[1] );
3809 $height = intval( $m[2] );
3811 $width = intval($match);
3813 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3819 # Strip bad stuff out of the alt text
3820 $alt = $this->replaceLinkHoldersText( $caption );
3821 $alt = Sanitizer
::stripAllTags( $alt );
3823 # Linker does the rest
3824 $sk =& $this->mOptions
->getSkin();
3825 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3829 * Set a flag in the output object indicating that the content is dynamic and
3830 * shouldn't be cached.
3832 function disableCache() {
3833 $this->mOutput
->mCacheTime
= -1;
3837 * Callback from the Sanitizer for expanding items found in HTML attribute
3838 * values, so they can be safely tested and escaped.
3839 * @param string $text
3840 * @param array $args
3844 function attributeStripCallback( &$text, $args ) {
3845 $text = $this->replaceVariables( $text, $args );
3846 $text = $this->unstripForHTML( $text );
3850 function unstripForHTML( $text ) {
3851 $text = $this->unstrip( $text, $this->mStripState
);
3852 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3860 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3861 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3862 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3868 function getTags() { return array_keys( $this->mTagHooks
); }
3874 * @package MediaWiki
3878 var $mText, # The output text
3879 $mLanguageLinks, # List of the full text of language links, in the order they appear
3880 $mCategories, # Map of category names to sort keys
3881 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3882 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
3883 $mVersion, # Compatibility check
3884 $mTitleText, # title text of the chosen language variant
3885 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3886 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3887 $mImages, # DB keys of the images used, in the array key only
3888 $mExternalLinks; # External link URLs, in the key only
3890 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3891 $containsOldMagic = false, $titletext = '' )
3893 $this->mText
= $text;
3894 $this->mLanguageLinks
= $languageLinks;
3895 $this->mCategories
= $categoryLinks;
3896 $this->mContainsOldMagic
= $containsOldMagic;
3897 $this->mCacheTime
= '';
3898 $this->mVersion
= MW_PARSER_VERSION
;
3899 $this->mTitleText
= $titletext;
3900 $this->mLinks
= array();
3901 $this->mTemplates
= array();
3902 $this->mImages
= array();
3903 $this->mExternalLinks
= array();
3906 function getText() { return $this->mText
; }
3907 function getLanguageLinks() { return $this->mLanguageLinks
; }
3908 function getCategoryLinks() { return array_keys( $this->mCategories
); }
3909 function &getCategories() { return $this->mCategories
; }
3910 function getCacheTime() { return $this->mCacheTime
; }
3911 function getTitleText() { return $this->mTitleText
; }
3912 function &getLinks() { return $this->mLinks
; }
3913 function &getTemplates() { return $this->mTemplates
; }
3914 function &getImages() { return $this->mImages
; }
3915 function &getExternalLinks() { return $this->mExternalLinks
; }
3917 function containsOldMagic() { return $this->mContainsOldMagic
; }
3918 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3919 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3920 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
3921 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3922 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3923 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3925 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
3926 function addImage( $name ) { $this->mImages
[$name] = 1; }
3927 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
3928 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
3930 function addLink( $title, $id ) {
3931 $ns = $title->getNamespace();
3932 $dbk = $title->getDBkey();
3933 if ( !isset( $this->mLinks
[$ns] ) ) {
3934 $this->mLinks
[$ns] = array();
3936 $this->mLinks
[$ns][$dbk] = $id;
3939 function addTemplate( $title, $id ) {
3940 $ns = $title->getNamespace();
3941 $dbk = $title->getDBkey();
3942 if ( !isset( $this->mTemplates
[$ns] ) ) {
3943 $this->mTemplates
[$ns] = array();
3945 $this->mTemplates
[$ns][$dbk] = $id;
3952 function merge( $other ) {
3953 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3954 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3955 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3959 * Return true if this cached output object predates the global or
3960 * per-article cache invalidation timestamps, or if it comes from
3961 * an incompatible older version.
3963 * @param string $touched the affected article's last touched timestamp
3967 function expired( $touched ) {
3968 global $wgCacheEpoch;
3969 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3970 $this->getCacheTime() < $touched ||
3971 $this->getCacheTime() <= $wgCacheEpoch ||
3972 !isset( $this->mVersion
) ||
3973 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3978 * Set options of the Parser
3980 * @package MediaWiki
3984 # All variables are private
3985 var $mUseTeX; # Use texvc to expand <math> tags
3986 var $mUseDynamicDates; # Use DateFormatter to format dates
3987 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3988 var $mAllowExternalImages; # Allow external images inline
3989 var $mAllowExternalImagesFrom; # If not, any exception?
3990 var $mSkin; # Reference to the preferred skin
3991 var $mDateFormat; # Date format index
3992 var $mEditSection; # Create "edit section" links
3993 var $mNumberHeadings; # Automatically number headings
3994 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3995 var $mTidy; # Ask for tidy cleanup
3997 function getUseTeX() { return $this->mUseTeX
; }
3998 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3999 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4000 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4001 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4002 function &getSkin() { return $this->mSkin
; }
4003 function getDateFormat() { return $this->mDateFormat
; }
4004 function getEditSection() { return $this->mEditSection
; }
4005 function getNumberHeadings() { return $this->mNumberHeadings
; }
4006 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4007 function getTidy() { return $this->mTidy
; }
4009 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4010 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4011 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4012 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4013 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4014 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4015 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4016 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4017 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4018 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4019 function setSkin( &$x ) { $this->mSkin
=& $x; }
4021 function ParserOptions() {
4023 $this->initialiseFromUser( $wgUser );
4027 * Get parser options
4030 function newFromUser( &$user ) {
4031 $popts = new ParserOptions
;
4032 $popts->initialiseFromUser( $user );
4036 /** Get user options */
4037 function initialiseFromUser( &$userInput ) {
4038 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4039 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4040 $fname = 'ParserOptions::initialiseFromUser';
4041 wfProfileIn( $fname );
4042 if ( !$userInput ) {
4044 $user->setLoaded( true );
4046 $user =& $userInput;
4049 $this->mUseTeX
= $wgUseTeX;
4050 $this->mUseDynamicDates
= $wgUseDynamicDates;
4051 $this->mInterwikiMagic
= $wgInterwikiMagic;
4052 $this->mAllowExternalImages
= $wgAllowExternalImages;
4053 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4054 wfProfileIn( $fname.'-skin' );
4055 $this->mSkin
=& $user->getSkin();
4056 wfProfileOut( $fname.'-skin' );
4057 $this->mDateFormat
= $user->getOption( 'date' );
4058 $this->mEditSection
= true;
4059 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4060 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4061 $this->mTidy
= false;
4062 wfProfileOut( $fname );
4067 * Callback function used by Parser::replaceLinkHolders()
4068 * to substitute link placeholders.
4070 function &wfOutputReplaceMatches( $matches ) {
4071 global $wgOutputReplace;
4072 return $wgOutputReplace[$matches[1]];
4076 * Return the total number of articles
4078 function wfNumberOfArticles() {
4079 global $wgNumberOfArticles;
4082 return $wgNumberOfArticles;
4086 * Return the number of files
4088 function wfNumberOfFiles() {
4089 $fname = 'Parser::wfNumberOfFiles';
4091 wfProfileIn( $fname );
4092 $dbr =& wfGetDB( DB_SLAVE
);
4093 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
4094 wfProfileOut( $fname );
4100 * Get various statistics from the database
4103 function wfLoadSiteStats() {
4104 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4105 $fname = 'wfLoadSiteStats';
4107 if ( -1 != $wgNumberOfArticles ) return;
4108 $dbr =& wfGetDB( DB_SLAVE
);
4109 $s = $dbr->selectRow( 'site_stats',
4110 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4111 array( 'ss_row_id' => 1 ), $fname
4114 if ( $s === false ) {
4117 $wgTotalViews = $s->ss_total_views
;
4118 $wgTotalEdits = $s->ss_total_edits
;
4119 $wgNumberOfArticles = $s->ss_good_articles
;
4125 * Basically replacing " > and < with HTML entities ( ", >, <)
4127 * @param string $in Text that might contain HTML tags
4128 * @return string Escaped string
4130 function wfEscapeHTMLTagsOnly( $in ) {
4132 array( '"', '>', '<' ),
4133 array( '"', '>', '<' ),